# utils/crypto.py
from cryptography.fernet import Fernet
from django.conf import settings
import base64


# 密码 在settings中生成
# from cryptography.fernet import Fernet
# def get_fernet_key():
#     # 从设置中获取密钥或生成一个
#     return Fernet.generate_key().decode("utf-8")
#
# # 对邮件信息加密密码
# KEY_EMAIL  = get_fernet_key()



def encrypt_data(data):
    """加密数据"""
    f = Fernet(settings.KEY_EMAIL)
    if isinstance(data, str):
        data = data.encode('utf-8')
    encrypted_data = f.encrypt(data)
    return base64.b64encode(encrypted_data).decode('utf-8')



def decrypt_data(encrypted_data):
    """解密数据"""
    f = Fernet(settings.KEY_EMAIL)
    encrypted_data = base64.urlsafe_b64decode(encrypted_data.encode('utf-8'))
    decrypted_data = f.decrypt(encrypted_data)
    return decrypted_data.decode('utf-8')

